﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzDesk.Attendance.MobileWeb.ViewModel;
using EzDesk.Attendance.MobileWeb.Controllers.Attendance;
using EzDesk.Attendance.AttendanceImpl;
using EzDesk.Attendance.Model;
using EzDesk.EzAppApi.Utility.EzDeskAppApi;
using EzDesk.EzAppApi.Utility.Models;
using EzDesk.EzAppApi.Web.Utility.Attributes;
using System.Text;

namespace EzDesk.Attendance.MobileWeb.Controllers
{
    public class AttendanceController : AttendanceBaseController
    {
        #region [ 构造器 ]
        public AttendanceController(AttendanceService attendanceService)
        {
            this._attendanceService = attendanceService;
        }


        public AttendanceController()
            :this(new AttendanceService())
        {
        }
        #endregion

        [HttpGet]
        [EzDeskAppSessionAuthorize]
        public ActionResult Task(Guid? userId)
        {
            AppTaskCollection taskCollection = new AppTaskCollection();
            taskCollection.AddTask("手工考勤", "手工进行考勤", "/attendance/checkattendance");

            ViewData.Model = taskCollection;
            Response.ContentType = "";
            return new ContentResult()
            {
                ContentType = "text/xml",
                ContentEncoding = Encoding.UTF8,
                Content = taskCollection.ToXmlString(),
            };
        }

        // GET
        // /Attendance/Index

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [EzDeskAppSessionAuthorize]
        [AttendanceRoleAuthorizeActionFilter(AttendanceRoles = "Employee,Manager")]
        public ActionResult Index()
        {
            //var role = CurrentRoles;

            ////如果参加考勤，则显示本周考勤记录
            ////如果管理考勤，则显示最近的员工当天考勤记录

            //Dictionary<SimpleUser, AttendanceEvaluationInfo> attendanceInfos;
            //var attendanceCountInfo = getDayAttendanceInfo(DateTime.Today, out attendanceInfos);
            //ViewData["dayAttendanceInfo"] = attendanceCountInfo;
            return View();

        }

        // GET
        // /Attendance/CheckAttendance
        /// <summary>
        /// 打考勤页面 手机页面仅作为示例
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [EzDeskAppSessionAuthorize]
        [AttendanceRoleAuthorizeActionFilter(AttendanceRoles = "Employee")]
        public ActionResult CheckAttendance()
        {
            DateTime today = DateTime.Today;
            // 1. 获得自己当天考勤，确定自己本次考勤类型
            IList<AttendanceInfo> myAttendanceInfos = _attendanceService.GetAttendanceInfoByUser(CurrentUserId, DateTime.Today);

            AttendanceInfo lastAttendanceInfo = null;
            if (myAttendanceInfos != null)
            {
                lastAttendanceInfo = myAttendanceInfos.LastOrDefault();
            }
            
            DutyTypeEnum dutyType;
            if (lastAttendanceInfo == null || lastAttendanceInfo.DutyType == DutyTypeEnum.OffDuty)
            {
                dutyType = DutyTypeEnum.OnDuty; // 这回应该上班
            }       
            else
            {
                dutyType = DutyTypeEnum.OffDuty; //这回应该下班
            }

            bool isExtraWork = false;
            if (lastAttendanceInfo != null && lastAttendanceInfo.IsExtraWork && lastAttendanceInfo.DutyType == DutyTypeEnum.OnDuty)
            {
                isExtraWork = true;
            }


            ViewData["dutyType"] = dutyType;
            ViewData["isExtraWork"] = isExtraWork;
            ViewData["myAttendanceInfos"] = myAttendanceInfos;

            return View();
        }


        // POST
        // /Attendance/CheckAttendance

        /// <summary>
        /// 打考勤页面 手机页面仅作为示例
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [EzDeskAppSessionAuthorize]
        [AttendanceRoleAuthorizeActionFilter(AttendanceRoles = "Employee")]
        public ActionResult CheckAttendance(string dutyTypeStr, string explaination, string applyForNoFault)
        {
            DutyTypeEnum dutyType;
            if (dutyTypeStr == "OnDuty")
            {
                dutyType = DutyTypeEnum.OnDuty;
            }
            else if (dutyTypeStr == "OffDuty")
            {
                dutyType = DutyTypeEnum.OffDuty;
            }
            else
            {
                //todo: error
                throw new Exception();
            }

            try{
                _attendanceService.CheckAttendance(CurrentUserId, dutyType, DateTime.Now, explaination);

                if (!String.IsNullOrEmpty(applyForNoFault))
                {
                    //申请考勤免责
                    _attendanceService.ApplyForCustmizedShiftWork(CurrentUserId, DateTime.Today, 0, explaination);
                }

                return ReturnView("CheckAttendance", "Attendance", "考勤完成", null);
            }catch(Exception ex)
            {
                //考勤出错
                return ReturnView("CheckAttendance", "Attendance", ex.Message, null);
            }            
        }

        // GET
        // /Attendance/AttendanceDetail

        /// <summary>
        /// 列出某个用户某一天的考勤信息
        /// </summary>
        /// <returns></returns>
        //[Authorize]
        //[EzDeskAppSessionAuthorize]
        //[AttendanceRoleAuthorizeActionFilter(AttendanceRoles = "Employee,Manager")]
        //public ActionResult AttendanceDetail(Guid userId, DateTime? day)
        //{
        //    if (String.IsNullOrEmpty(userIdStr))
        //    {
        //        userIdStr = CurrentUserId.ToString();
        //    }
        //    DateTime today = day.GetValueOrDefault(DateTime.Today);

        //    var attendanceInfo = _attendanceService.GetEvaluatedAttendanceInfo(userIdStr, day.GetValueOrDefault());

        //    ViewData["userInfo"] = apiClient.GetSimpleUserInfos(userIdStr).FirstOrDefault();
            
        //    ViewData["hasApplyShiftWorkChange"] = true;

        //    return View(attendanceInfo);
        //}

        //private AttendanceCountViewModel getDayAttendanceInfo(DateTime day, out Dictionary<SimpleUser, AttendanceEvaluationInfo> attendanceInfos)
        //{
        //    var userList = apiClient.GetSimpleUserInfos(
        //        _attendanceService.GetAttendanceConfig().AttendanceUserIds
        //        );
        //    attendanceInfos = new Dictionary<SimpleUser, AttendanceEvaluationInfo>();

        //    int lateCount = 0;
        //    int earlyCount = 0;
        //    int absenceCount = 0;
        //    int leaveCount = 0;

        //    foreach (var user in userList)
        //    {
        //        var info = _attendanceService.GetEvaluatedAttendanceInfo(user.Id.ToString(), day);
        //        attendanceInfos.Add(user, info);
        //        attendanceCountCalculate(ref lateCount, ref earlyCount, ref absenceCount, ref leaveCount, info);
        //    }

        //    return new AttendanceCountViewModel()
        //    {
        //        LateCount = lateCount,
        //        EarlyCount = earlyCount,
        //        AbsenceCount = absenceCount,
        //        LeaveCount = leaveCount,
        //    };
        //}


        // GET
        // /Attendance/WeekInfo

        /// <summary>
        /// 显示本人一周考勤记录
        /// </summary>
        /// <returns></returns>
        //[Authorize]
        //[EzDeskAppSessionAuthorize]
        //public ActionResult MyWeekAttendance(int? year, int? days)
        //{

        //    var userIdStr = CurrentUserId.ToString();

        //    // 简单的权限控制
        //    if (!AttendanceConfig.Cfg.AttendanceUserIds.Contains(userIdStr))
        //    {
        //        //TODO: 认证错误
        //        throw new Exception();
        //    }


        //    DateTime timePoint = DateTime.Now;
        //    if (year.HasValue && days.HasValue)
        //    {
        //        timePoint = new DateTime(year.Value, 1, 1);
        //        timePoint = timePoint.AddDays(days.Value);
        //    }

        //    // get start & end of this week
        //    DateTime weekStart;
        //    DateTime weekEnd;
        //    DateTimeHelper.GetAWeek(timePoint, out weekStart, out weekEnd);
        //    ViewData["weekStart"] = weekStart;
        //    ViewData["weekEnd"] = weekEnd;

        //    // calculate lastweek and nextweek
        //    ViewData["thisWeek"] = timePoint;
        //    ViewData["lastWeek"] = timePoint.AddDays(-7);
        //    ViewData["nextWeek"] = timePoint.AddDays(7);



        //    IList<AttendanceEvaluationInfo> modelItems = new List<AttendanceEvaluationInfo>();

        //    // generate the calander (of this week)
        //    for (DateTime date = weekStart; date <= weekEnd; date = date.AddDays(1))
        //    {
        //        // we don't display days in the future
        //        if (date <= DateTime.Now)
        //        {
        //            modelItems.Add(
        //                _attendanceService.GetEvaluatedAttendanceInfo(userIdStr, date)
        //                );
        //        }
        //    }
        //    return View(modelItems);
        //}




        // GET
        // /Attendance/DayAttendance
        /// <summary>
        /// 显示当日考勤记录
        /// </summary>
        /// <returns></returns>
        //[Authorize]
        //[EzDeskAppSessionAuthorize]
        //public ActionResult DayAttendance()
        //{
        //    //todo 权限控制

        //    var today = DateTime.Today;
        //    ViewData["theDay"] = today;
        //    var userList = apiClient.GetSimpleUserInfos(
        //        _attendanceService.GetAttendanceConfig().AttendanceUserIds
        //        );
        //    Dictionary<SimpleUser, AttendanceEvaluationInfo> model = new Dictionary<SimpleUser, AttendanceEvaluationInfo>();

        //    int lateCount = 0;
        //    int earlyCount = 0;
        //    int absenceCount = 0;
        //    int leaveCount = 0;

        //    foreach (var user in userList)
        //    {
        //        var info = _attendanceService.GetEvaluatedAttendanceInfo(user.Id.ToString(), today);
        //        model.Add(user, info);
        //        attendanceCountCalculate(ref lateCount, ref earlyCount, ref absenceCount, ref leaveCount, info);
        //    }

        //    ViewData["dayAttendanceInfo"] = new AttendanceCountViewModel()
        //    {
        //        LateCount = lateCount,
        //        EarlyCount = earlyCount,
        //        AbsenceCount = absenceCount,
        //        LeaveCount = leaveCount,
        //    };

        //    return View(model);
        //}

        //private static void attendanceCountCalculate(ref int lateCount, ref int earlyCount, ref int absenceCount, ref int leaveCount, AttendanceEvaluationInfo info)
        //{
        //    if (info.IsLate)
        //    {
        //        lateCount++;
        //    }
        //    if (info.IsEarlyLeave)
        //    {
        //        earlyCount++;
        //    }
        //    if (info.IsAbsence)
        //    {
        //        absenceCount++;
        //    }
        //    if (info.LeaveInfo.IsWholeDay)
        //    {
        //        leaveCount++;
        //    }
        //}


        // GET
        // /Attendance/Manhour

        ///// <summary>
        ///// 显示当前用户的工时和年假信息
        ///// </summary>
        ///// <returns></returns>
        
        //[EzDeskAppSessionAuthorize]
        //public ActionResult Manhour()
        //{
        //    return View();
        //}



        // GET
        // /Attewndance/ApplyNewLeave

        //[EzDeskAppSessionAuthorize]
        //public ActionResult ApplyNewLeave()
        //{
        //    // todo 判断是否有申请假期的权限

        //    var leaveTypes = _attendanceService.GetAllLeaveTypes().ToList();

        //    ViewData["leaveTypeList"] = new SelectList(leaveTypes, "LeaveTypeId", "LeaveTypeName");


        //    //默认时间为从明天上班到明天下班
        //    DateTime today = DateTime.Today;
        //    DateTime tomorrow = today.AddDays(1);
        //    ViewData["startYear"] = tomorrow.Year;
        //    ViewData["startMonth"] = tomorrow.Month;
        //    ViewData["startDay"] = tomorrow.Day;

        //    ViewData["endYear"] = tomorrow.Year;
        //    ViewData["endMonth"] = tomorrow.Month;
        //    ViewData["endDay"] = tomorrow.Day;

        //    var hoursToChooseList = getHoursToChooseList();
        //    var miniutesToChooseList = getMiniutesToChooseList();

        //    ViewData["startHour"] = new SelectList(hoursToChooseList);
        //    ViewData["startMiniute"] = new SelectList(miniutesToChooseList);
        //    ViewData["endHour"] = new SelectList(hoursToChooseList, hoursToChooseList.Last());
        //    ViewData["endMiniute"] = new SelectList(miniutesToChooseList, miniutesToChooseList.Last()) ;

        //    return View();
        //}

        
        // POST
        // /Attewndance/ApplyNewLeave
        //[AcceptVerbs(HttpVerbs.Post)]
        //[Authorize]
        //[EzDeskAppSessionAuthorize]
        //public ActionResult ApplyNewLeave(
        //    string leaveTypeList,
        //    int startYear, int startMonth, int startDay, int startHour, int startMiniute,
        //    int endYear, int endMonth, int endDay, int endHour, int endMiniute,
        //    string description
        //    )
        //{
        //    // todo 是否具有处理申请权限
        //    //试图添加，成功则跳转到 LeaveDetail

        //    DateTime startTime = new DateTime(startYear, startMonth, startDay, startHour, startMiniute, 0);
        //    DateTime endTime = new DateTime(endYear, endMonth, endDay, endHour, endMiniute, 0);
        //    string leaveTypeIdStr = leaveTypeList;

        //    try
        //    {
        //        string leaveIdStr = _attendanceService.ApplyForNewLeave(CurrentUserId.ToString(), leaveTypeIdStr, startTime, endTime, description);
        //        return ReturnView("LeaveDetail", "Attendance", "假期申请成功！", new { leaveId = leaveIdStr });
        //    }
        //    catch (Exception ex)
        //    {
        //        SetReturnInfoText("假期申请失败" + ex.Message);
        //        return RedirectToAction("ApplyNewLeave");
        //    }
        //}

        // GET
        // /Attendance/LeaveDetail
        //[EzDeskAppSessionAuthorize]
        //public ActionResult LeaveDetail(Guid? leaveId)
        //{
        //    //todo: 获得当前用户对这个假期的权限
        //    if (!leaveId.HasValue)
        //    {
        //        throw new Exception();
        //    }

        //    var leaveInfo = _attendanceService.GetLeaveInfo(leaveId.Value);

        //    if (leaveInfo == null)
        //    {
        //        throw new Exception();
        //    }

        //    ViewData["applyUserProfile"] = apiClient.GetUserProfileById(leaveInfo.UserId);
        //    return View(leaveInfo);
        //}

        // POST
        // /Attendance/AuditLeaveInfo
        
        //[Authorize]
        //[AcceptVerbs(HttpVerbs.Post)]
        //[EzDeskAppSessionAuthorize]
        //public ActionResult AuditLeaveInfo(Guid? leaveId, string auditNote, string r)
        //{
        //    try
        //    {
        //        _attendanceService.AuditLeaveInfo(leaveId.GetValueOrDefault(), CurrentUserId.ToString(), auditNote);
        //        SetReturnInfoText("审核成功");
        //    }
        //    catch (Exception /*ex*/)
        //    {
        //        SetReturnInfoText("审核出错");
        //    }
        //    return RedirectToAction("LeaveDetail", new { leaveId = leaveId });
        //}


        //#region [ LeaveInfo Controllers ]

        //// GET
        //// /Attendance/MyLeaves

        //[Authorize]
        //[EzDeskAppSessionAuthorize]
        //public ActionResult MyLeaves(DateTime? theDay)
        //{
        //    if (theDay == null)
        //    {
        //        theDay = DateTime.Today;
        //    }
        //    Guid userId = CurrentUserId.ToString();

        //    // 之前一个月开始的所有假期
        //    DateTime startDate;
        //    DateTime endDate;
        //    DateTimeHelper.GetAMonth(theDay.GetValueOrDefault(), out startDate, out endDate);

        //    ViewData["theDay"] = theDay.GetValueOrDefault();
        //    ViewData["lastMonth"] = theDay.GetValueOrDefault().AddMonths(-1);
        //    ViewData["nextMonth"] = theDay.GetValueOrDefault().AddMonths(1);

        //    var leaveList = _attendanceService.GetLeaveInfo(CurrentUserId.ToString(), startDate, endDate);

        //    return View(leaveList);
        //}


        //#endregion


        //#region [ private methods ]

        //private IList<int> getHoursToChooseList()
        //{
        //    IList<int> hourList = new List<int>();
        //    int startTime = _attendanceService.GetAttendanceConfig().StdOnDutyTime.Hour;
        //    int endTime = _attendanceService.GetAttendanceConfig().StdOffDutyTime.Hour;
        //    for (int i = startTime; i <= endTime; i++)
        //    {
        //        hourList.Add(i);
        //    }
        //    return hourList;
        //}

        //private IList<int> getMiniutesToChooseList()
        //{
        //    IList<int> miniutesList = new List<int>()
        //    {
        //        0, 30,
        //    };
        //    return miniutesList;
        //}
        //#endregion
    }
}
